package mongo;

import ip.IpCreator;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import net.sunniwell.tools.system.IpUtil;

import org.apache.commons.lang.math.RandomUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import util.OsCreator;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class MongoDB4CRUDTest {
	private Mongo mg = null;
    private DB db;
    private DBCollection devices;
    
    @Before
    public void init() {
        try {
            mg = new Mongo();
            //mg = new Mongo("localhost", 27017);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (MongoException e) {
            e.printStackTrace();
        }
        //获取temp DB；如果默认没有创建，mongodb会自动创建
        db = mg.getDB("temp");
        //获取devices DBCollection；如果默认没有创建，mongodb会自动创建
        devices = db.getCollection("devices");
    }
    
    @After
    public void destory() {
        if (mg != null)
            mg.close();
        mg = null;
        db = null;
        devices = null;
        System.gc();
    }
    
    @Test
    public void add() {
    	long count = devices.count();
    	if(count>0) return;
    	List<DBObject> list = new ArrayList<DBObject>();
    	for (int i = 0; i < 500000; i++) {
    		DBObject device = new BasicDBObject();
            device.put("sn", "sn"+RandomUtils.nextInt(999999)+"_"+i);
            device.put("aliasName", "alias"+RandomUtils.nextInt(999999)+"_"+i);
            device.put("softwareVersion", "sv"+RandomUtils.nextInt(999999)+"_"+i);
            String ip = IpCreator.getRandomIp();
            device.put("ip", ip);
            device.put("digitIp", IpUtil.iptolong(ip));
            device.put("os", OsCreator.getRandomOS());
            list.add(device);
		}
        devices.insert(list);
    }
    
    @Test
    public void query(){
//    	System.out.println();
    	long start = System.currentTimeMillis();
    	DBObject dbObject = new BasicDBObject();
    	dbObject.put("sn", "sn433769_16");
    	dbObject.put("os", "Linux");
    	List<DBObject> list = devices.find(dbObject).toArray();
    	System.out.println(list.size());
    	System.out.println("用时："+(System.currentTimeMillis()-start)+"毫秒");
    }
    
}
